class WorksController < ApplicationController

  before_filter :get_users_and_attendees, :only => [:update, :edit, :new]
  before_filter :check_attendee, :except => [ :index ]
  before_filter :check_deadline, :except => [:index, :show, :edit, :update]

  # GET /works
  # GET /works.xml
  def index

    if authorized?
   	  @works = Work.find(:all)
 	  else
 	    @works = current_user ? current_user.works : []
    end

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @works }
    end
  end

  # GET /works/1
  # GET /works/1.xml
  def show
    @work = Work.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @work }
    end
  end

  # GET /works/new
  # GET /works/new.xml
  def new
    @work = Work.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @work }
    end
  end

  # GET /works/1/edit
  def edit
    @work = Work.find(params[:id])
  end

  # POST /works
  # POST /works.xml
  def create
    @work = Work.new(params[:work])

    respond_to do |format|

      v = Proc.new { |user| user.works << @work ; user.save }

      if @work.save and v.call(current_user)
        flash[:notice] = 'Trabalho enviado.'
        format.html { redirect_to(@work) }
        format.xml  { render :xml => @work, :status => :created, :location => @work }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @work.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /works/1
  # PUT /works/1.xml
  def update
    @work = Work.find(params[:id])

    respond_to do |format|
      if @work.update_attributes(params[:work])
        flash[:notice] = 'Dados do trabalho atualizados.'
        format.html { redirect_to(@work) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @work.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /works/1
  # DELETE /works/1.xml
  def destroy
    @work = Work.find(params[:id])
    @work.destroy

    respond_to do |format|
      format.html { redirect_to(works_url) }
      format.xml  { head :ok }
    end
  end

  def get_users_and_attendees
     @users = @work ? @work.users : []

     @author = Attendee.find(:first, :conditions => { :user_login => current_user.login }) if current_user.has_attendee?

     @authors = @users.map { |u| Attendee.find(:first, :conditions => { :user_login => u.login }) }

    @probable_attendees = Attendee.find(:all,
                          :conditions => { :ies => @author.ies, :pet => @author.pet} ) - @authors
  end

  def check_deadline
    deadline = Date.new(2010,05,17)

    if Date.current > deadline && !authorized?
      flash[:notice] = "Não é mais possível mandar ou apagar trabalhos."
      redirect_to works_path
    end

  end

  private :get_users_and_attendees

end
